package top.hepingan.java.service.Impl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import top.hepingan.java.entity.Bottle;
import top.hepingan.java.entity.Pickup;
import top.hepingan.java.mapper.BottleMapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.hepingan.java.mapper.PickupMapper;
import top.hepingan.java.service.Impl.service.IBottleService;
import top.hepingan.java.utils.UserUtils;

import java.time.LocalDateTime;

/**
 * <p>
 * 漂流瓶表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-10-28
 */
@Service
public class BottleServiceImpl extends ServiceImpl<BottleMapper, Bottle> implements IBottleService {

    @Autowired
    PickupMapper pickupMapper;
    @Override
    public boolean throwBottle(Bottle bottle) {
        bottle.setStatus(3);

        return save(bottle);
    }

    @Override
    public Bottle pickBottle() {
        //获取登录ID
        Long userId = UserUtils.getCurrentLoginId();
        //他来捞取 -随机--但是不能捞到自己的漂流瓶-然后创建出漂流瓶关系
        //自己捞取过的也不能捞取
        LambdaQueryWrapper<Bottle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(Bottle::getStatus, 3)
                .ne(Bottle::getUserId, userId)

                .last(" order by rand() limit 1");
        //除开自己外的漂流瓶
        Bottle bottle = getOne(queryWrapper);
        if (bottle == null) {
            return null;
        }
        /// 是否被捞取过
        LambdaQueryWrapper<Pickup> pickupQueryWrapper = new LambdaQueryWrapper<>();
        pickupQueryWrapper.eq(Pickup::getBottleId, bottle.getId());
        pickupQueryWrapper.eq(Pickup::getPickerId, userId);
        if (pickupMapper.selectOne(pickupQueryWrapper) != null) {
            return null;
        }
        if(bottle.getCishu()<=0)
        {
            return null;
        }
        //创建漂流瓶关系
        Pickup pickup = new Pickup();
        pickup.setBottleId(bottle.getId());
        pickup.setPickerId(userId);
        pickup.setPickupTime(LocalDateTime.now());

        pickupMapper.insert(pickup);
       //次数更新
        bottle.setCishu(bottle.getCishu()-1);
        updateById(bottle);
        return bottle;
    }

    @Override
    public boolean likeBottle(Long bottleId) {
        Bottle bottle = getById(bottleId);
        if (bottle != null) {
            bottle.setLikeCount(bottle.getLikeCount() + 1);
            return updateById(bottle);
        }
        return false;
    }
}
